const express = require("express");
const Router = express.Router();
const bodyParser = require("body-parser");
const { userList } = require("../../db/sql/db");
const db = require("../../db/sql/dbconfig");
const { json } = require("../../db/json");
// const md5 = require("blueimp-md5");
const { encryptPwd } = require("../../utils/format")
const { setToken } = require("../../utils/token");
const { updateTime } = require("../../utils/time.js")

Router.use(bodyParser.json());
Router.use(
  bodyParser.urlencoded({
    extended: false,
  })
);
Router.use(bodyParser.json());

// 注册(账号注册)
Router.post("/register", (req, res) => {
  let { user_name, password, phone } = req.body;
  if (!user_name || !password || !phone) {
    let result = "drop";
    json(res, result);
    return;
  }
  // 验证手机号码
  let reg = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/;
  if (!reg.test(phone)) {
    res.json({
      code: 500,
      msg: "手机号码格式不正确,请重新输入",
    });
    return;
  }
  // 查询是否有该账号
  db(userList.queryUser, [user_name], (data) => {
    if (!data.length) {
      let no_encrypt = password
      password = encryptPwd(password);
      let update = updateTime()
      db(userList.insert, [user_name, password, no_encrypt, phone, update], (result) => {
        let type = "register";
        json(res, type);
      });
    } else {
      res.json({
        code: 500,
        msg: "该账号已被注册,请重新注册",
      });
    }
  });
});

// 登录
Router.post("/login", (req, res) => {
  let { user_name, password } = req.body;
  user_name = user_name.trim()
  password = password.trim()
  if (!user_name || !password) {
    let result = "drop";
    json(res, result);
    return;
  }
  // 验证数据库是否有存在记录
  db(userList.queryUser, [user_name], (data) => {
    if (!data.length)
      res.json({ code: 500, msg: "你还没有账号,请注册完成后再登录" });
    else password = encryptPwd(password);
    db(userList.queryLogin, [user_name, password], (result) => {
      if (result.length) {
        // 登录成功
        let token = setToken(user_name, password); // 一个小时
        // 获取用户id
        let user_id
        db(userList.queryUserId, [user_name], (d) => {
          d.reduce((r, item, index) => {
            user_id = item.user_id
          }, [])
          res.send({
            code: 0,
            msg: "登录成功!!",
            token,
            user_id,
          });
        });
      } else {
        // 密码错误
        res.json({
          code: 500,
          msg: "密码错误,请重新输入",
        });
      }
    });
  });
});
// 第三方登录
Router.post("/other/login", (req, res) => {
  // 性别
  // 头像
  // 昵称
  let { gender, nick_name, avatar } = req.body;
});
// 扫码登录
Router.post("/code", (req, res) => { });

module.exports = Router;
